#include "gamearea.h"
#include <QPainter>
#include <QKeyEvent>
#include <QtGlobal> // 包含 qrand()
#include <ctime>    // 包含 time()

GameArea::GameArea(QWidget *parent)
    : QWidget(parent), direction(10, 0)
{
    setFixedSize(400, 400);
    snake.append(QPoint(200, 200));
    generateFood();
    timerId = startTimer(100);

    // 初始化随机数生成器
    qsrand(static_cast<uint>(time(nullptr)));
}

void GameArea::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.fillRect(rect(), Qt::black);

    painter.setBrush(Qt::green);
    for (const QPoint &point : snake) {
        painter.drawRect(point.x(), point.y(), 10, 10);
    }

    painter.setBrush(Qt::red);
    painter.drawRect(food.getPosition().x(), food.getPosition().y(), 10, 10);
}

void GameArea::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == timerId) {
        moveSnake();
        checkCollision();
        update();
    }
}

void GameArea::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_Left:
        if (direction != QPoint(10, 0)) direction = QPoint(-10, 0);
        break;
    case Qt::Key_Right:
        if (direction != QPoint(-10, 0)) direction = QPoint(10, 0);
        break;
    case Qt::Key_Up:
        if (direction != QPoint(0, 10)) direction = QPoint(0, -10);
        break;
    case Qt::Key_Down:
        if (direction != QPoint(0, -10)) direction = QPoint(0, 10);
        break;
    }
}

void GameArea::moveSnake()
{
    QPoint head = snake.first();
    head += direction;
    snake.prepend(head);

    if (head == food.getPosition()) {
        generateFood();
    } else {
        snake.removeLast();
    }
}

void GameArea::checkCollision()
{
    QPoint head = snake.first();
    if (head.x() < 0 || head.x() >= width() || head.y() < 0 || head.y() >= height()) {
        killTimer(timerId);
        // 处理游戏结束
    }

    for (int i = 1; i < snake.size(); ++i) {
        if (snake[i] == head) {
            killTimer(timerId);
            // 处理游戏结束
        }
    }
}

void GameArea::generateFood()
{
    QPoint newPosition;
    do {
        newPosition = QPoint((qrand() % (width() / 10)) * 10,
                             (qrand() % (height() / 10)) * 10);
    } while (snake.contains(newPosition));
    food.setPosition(newPosition);
}
